unit uAppLog;

interface

uses
  SysUtils, Windows, uDZThread, uDzProcess, uDZTrace, uDZSysUtils, 
  DLSystemFolderPath, uAppCmdLineParams, uAppConst;

procedure WriteLog(sev: TDzTraceSeverity; const s: string);
procedure FmtWriteLog(sev: TDzTraceSeverity; const fmt: string;
  const args: array of const);
procedure LogException(E: Exception);

implementation

var
  CriticalSection: TDzCriticalSection;
  Trace: IDzTrace;

procedure WriteLog(sev: TDzTraceSeverity; const s: string);
begin
  if not CmdLineParams.DebugMode then Exit;
  CriticalSection.Acquire;
  try
    if not Assigned(Trace) then
    try
      if CmdLineParams.LogType = altConsole then
      begin
        Windows.AllocConsole;
        Trace := TConsoleTrace.Create;
      end
      else begin
        Trace := TDzFileTrace.Create(PathOfAppData + CWorkDirectory  + '\client.log');
      end;
      Trace.Attributes['Encodding'] := teAnsi;
      Trace.DateTimeFormat := 'yyyy-mm-dd hh:nn:ss';
    except
      Exit;
    end;
    Trace.Write(sev, s);
  finally
    CriticalSection.Release;
  end;
end;

procedure FmtWriteLog(sev: TDzTraceSeverity; const fmt: string;
  const args: array of const);
begin
  WriteLog(sev, Format(fmt, args));
end;

procedure LogException(E: Exception);
begin
  WriteLog(tsError, Format('%s: %s'#10, [E.ClassName, E.Message]));
end;

initialization
  CriticalSection := TDzCriticalSection.Create(500);
  
finalization
  CriticalSection.Free;

end.
